#!/usr/bin/env node
const { spawn } = require('child_process');
const path = require('path');


const rollupConfig = path.resolve(__dirname, './rollup.config.js');


const SERVICES = [
  { name: 'rollup', cmd: 'npx', args: ['rollup', '-c', rollupConfig, '--watch'] },
  { name: 'dev', cmd: 'node', args: [path.resolve(__dirname, '../config/system.js')] },
];

const env = { ...process.env };

const children = SERVICES.map(({ name, cmd, args }) => {
  // 移除 stdio: 'inherit'，让输出通过管道传递以便添加前缀
  const child = spawn(cmd, args, { env, shell: true });

  // 给每条日志加前缀 [name]
  child.stdout.on('data', d => process.stdout.write(`[${name}] ${d}`));
  child.stderr.on('data', d => process.stderr.write(`[${name}] ${d}`));

  return child;
});

// 任意子进程退出 → 全杀 → 主进程退出
children.forEach(c => c.on('exit', (code) => {
  children.forEach(k => k.kill());
  process.exit(code);
}));

// Ctrl+C 友好退出
process.on('SIGINT', () => {
  console.log('\n🛑 收到中断信号，正在关闭...');
  children.forEach(c => c.kill('SIGINT'));
});

process.on('SIGTERM', () => {
  console.log('\n🛑 收到终止信号，正在关闭...');
  children.forEach(c => c.kill('SIGTERM'));
});
